/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.common.data.beetl.ami

import org.beetl.sql.annotation.entity.LogicDelete
import org.beetl.sql.core.SQLManager
import java.lang.reflect.Method
import org.beetl.sql.mapper.MapperInvoke

/**
 * 批量删除 beetl Ami
 * @author maoxiaodong
 */
class DeleteByIdsAmi : MapperInvoke() {

    override fun call(sm: SQLManager, entityClass: Class<*>, m: Method?, args: Array<out Any>): Any {
        val tableName = sm.dbStyle.nameConversion.getTableName(entityClass)
        val classDesc = sm.getClassDesc(entityClass)
        val table = sm.getTableDesc(tableName)
        val idNames = table.idNames
        val logicDeleteField = entityClass.declaredFields.find{it.isAnnotationPresent(LogicDelete::class.java)}
        val sql: String
        val ids = args[0] as List<*>

        if(logicDeleteField != null){
            sql = "update $tableName set del_flag = 0 where ${idNames.first()} in (#{join(ids)})"
        }else{
            sql = "delete from $tableName where ${idNames.first()} in (#{join(ids)})"
        }
        val params = mutableMapOf<String, Any>()
        params["ids"] = ids
        return sm.executeUpdate(sql, params)
    }
}